package com.jeecg.p3.baseApi.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jeecgframework.p3.core.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import net.sf.json.JSONObject;

public class ChatClient {

    private final static Logger logger = LoggerFactory.getLogger(ChatClient.class);

    public static String postMethod(String query, String userId) {
        try {
            PropertiesUtil propertiesUtil = new PropertiesUtil("jeewx.properties");
            String url_config = propertiesUtil.readProperty("difyUrl");
            URL url = new URL(url_config);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            String difyKey = propertiesUtil.readProperty("difyKey");
            connection.setRequestProperty("Authorization", "Bearer " + difyKey);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            // 使用Jackson库构建JSON
            // 导入Jackson库的ObjectMapper类
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode json = mapper.createObjectNode();
            json.putObject("inputs");
            json.put("query", query);
            json.put("response_mode", "streaming");
            json.put("conversation_id", "");
            json.put("user", userId);

            // 导入ArrayNode类，解决无法解析类型的问题
            ArrayNode files = json.putArray("files");
            ObjectNode file = files.addObject();
            file.put("type", "image");
            file.put("transfer_method", "remote_url");
            file.put("url", "");

            String jsonInput = mapper.writeValueAsString(json);

            OutputStream os = connection.getOutputStream();
            byte[] input = jsonInput.getBytes("utf-8");
            os.write(input, 0, input.length);

            int responseCode = connection.getResponseCode();

            // 处理错误响应
            if (responseCode >= 400) {
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "utf-8"));
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    errorResponse.append(line);
                }
                logger.error("错误响应: " + errorResponse);
                return "";
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String responseLine;
            StringBuilder finalAnswer = new StringBuilder();
            // 优化后的流式数据处理
            while ((responseLine = br.readLine()) != null) {
                if (responseLine.startsWith("data: {")) {
                    String jsonStr = responseLine.substring(6);
                    JSONObject node = JSONObject.fromObject(jsonStr);
                    String event = node.getString("event");
                    if ("agent_message".equals(event)) {
                        String answer = node.getString("answer");
                        finalAnswer.append(answer);
                    }
                }
            }
            return finalAnswer.toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "";
    }
}
